package com.controller.backend.work;

import com.entity.User;
import com.entity.Work;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/backend/works")
public class BackWorkServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Work> workList1 = new ArrayList<>();
        List<Work> workList2 = new ArrayList<>();
        String type1 = null;
        String type2 = null;
        String sql = "select * from work";
        try (Connection conn = DataSourceUtils.getConnection();
             PreparedStatement st = conn.prepareStatement(sql)) {
            try (ResultSet rs = st.executeQuery(sql)) {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String title = rs.getString("title");
                    String content = rs.getString("content");
                    String type = rs.getString("type");
                    Date addTime = rs.getDate("addtime");
                    Work work = new Work(id, title, content, type, addTime);
                    if (type.equals("就业工作")) {
                        workList1.add(work);
                        type1 = type;
                    } else if (type.equals("就业信息")) {
                        workList2.add(work);
                        type2 = type;
                    }
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        String toGo = req.getParameter("workType");
        if (toGo.equals("lw")) {
            req.setAttribute("works", workList1);
            req.setAttribute("worktype", type1);
        } else if (toGo.equals("li")) {
            req.setAttribute("works", workList2);
            req.setAttribute("worktype", type2);
        }
        User user = (User) req.getSession().getAttribute("user");
        if (user != null) {
            req.setAttribute("username", user.getUserName());
            req.getRequestDispatcher("/WEB-INF/backend/work.jsp").forward(req, resp);
        } else {
            resp.sendRedirect(req.getContextPath() + "/login");
        }
    }
}
